from PyQt6.QtCore import Qt, QRectF
from PyQt6.QtGui import QPainter
from PyQt6.QtWidgets import QWidget

from gui.utils import FLAG_ALIGN_LEFT, format_number, get_resource_icon
from gui.utils.size import WINDOW_WIDTH, RESOURCE_HEIGHT
from state.game_state import GameState
from state.resource import Resource
from utils.event_bus import EventBus

ResourceList = ('energy', 'mineral', 'food', 'customer', 'alloy')


class PanelResource(QWidget):
    def __init__(self, state: GameState, parent=None):
        super(PanelResource, self).__init__(parent)
        self.setGeometry(QRectF(0, 0, WINDOW_WIDTH, RESOURCE_HEIGHT).toRect())
        self.w = WINDOW_WIDTH / 5
        self.h = RESOURCE_HEIGHT
        self.half_h = RESOURCE_HEIGHT / 2

        EventBus.register('update_panel_resource', self.update)

        self.state: GameState = state
        self.res_panel = self.state.players[self.state.obverse].res_panel

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setBrush(Qt.GlobalColor.white)
        painter.drawRect(0, 0, WINDOW_WIDTH, RESOURCE_HEIGHT)

        for index, name in enumerate(ResourceList):
            painter.setPen(Qt.GlobalColor.black)
            sx = self.w * index

            painter.drawRect(QRectF(sx, 0, self.w - 1, RESOURCE_HEIGHT - 1))
            painter.drawPixmap(QRectF(sx, 0, self.h, self.h).toRect(), get_resource_icon(name))
            r: Resource = getattr(self.res_panel, name)

            painter.drawText(
                QRectF(sx + self.h + 5, 0, self.w - self.h, self.half_h),
                FLAG_ALIGN_LEFT,
                format_number(r.storage)
            )

            if r.daily < 0:
                painter.setPen(Qt.GlobalColor.red)

            painter.drawText(
                QRectF(sx + self.h + 5, self.half_h, self.w - self.h, self.half_h),
                FLAG_ALIGN_LEFT,
                ('+' if r.daily > 0 else '') + format_number(r.daily)
            )
